<?php
/*+---------------------------------------------------------------------------------------------------------------------------------------------
  |       站点数据库备份与恢复   
  +---------------------------------------------------------------------------------------------------------------------------------------------
  |       1.设置数据库地址、数据库账号、密码、以及备份文件存储路径
  +---------------------------------------------------------------------------------------------------------------------------------------------
  |       2.数据备份
  +---------------------------------------------------------------------------------------------------------------------------------------------
  |       2.1如果你想备份test库中的所有表，只要这样：$DbBak->backupDb('essgl');
  +---------------------------------------------------------------------------------------------------------------------------------------------
  |       2.2如果你只想备份test库中的admin 、test表，可以用一个一维数组指定：$DbBak->restoreDb('test',array("admin","test"));  
  +---------------------------------------------------------------------------------------------------------------------------------------------
  |       2.3如果只想备份一个表，比如admin表： //$DbBak->backupDb('test','admin'); 
  +---------------------------------------------------------------------------------------------------------------------------------------------
  |       数据恢复： 对于2.1、2.1、2.3三种情况，只要相应的修改下语句，把backupDb换成restoreDb就能实现数据恢复了： 
  |       $DbBak->restoreDb('test'); //SQL代码 //$DbBak->restoreDb('test',array('admin','test')); 
  |       PHP代码 //$DbBak->restoreDb('test','admin'); 
  +---------------------------------------------------------------------------------------------------------------------------------------------*/
class WebsiteDatabaseBackupAndRecoverAction extends CommonAction{
         /*+---------------------------------+
           |     管理备份文件                |
           +---------------------------------+*/
         public function manageBackupFiles(){
                //显示所有表信息
                $tab  = $this->allTable();
                $this ->assign("tableInfo",$this->ifBackUp($tab));
                $this ->display();
         }

         //管理所有备份文件
         public function executeBackupFiles(){
             $dataPATH = $_SERVER['DOCUMENT_ROOT'].__ROOT__."/WebsiteDatabaseBackUp/".$_SESSION[C("DATA_KEY")];
             //删除全部备份文件
             if($_POST['allDel']){
                 if(file_exists($dataPATH)){
                     $this->deleteDir($dataPATH);
                 }
                 if(!file_exists($dataPATH)){
                        $this->success("备份文件全部删除成功！");
                 }else{
                        $this->error("备份文件全部删除失败！");
                 }
             }

             //删除表备份
             if($_POST['del']){
                 $num       = count($_POST['tableName']);
                 if($num == 0){
                      $this->error("请勾选要删除的表！");
                 }elseif($num > 1){
                      $table  = $_POST['tableName'];
                 }
                 foreach($table as $key => $val){
                     $tablePATH = $dataPATH."/".$val;
                     
                     if(file_exists($tablePATH)){
                           $errorDelTab[] = $val;
                     }
                     if(file_exists($tablePATH)){
                           $errorDelTab[] = $val;
                     }
                 }
                 if($errorDelTab == null){
                     $success = "表：";
                     foreach($table as $key => $val){
                             $success .= "{$val} =》删除成功！<br/>";
                     }
                     $this->success($success);
                 }else{
                     $error = "表：";
                     foreach($errorDelTab as $key => $val){
                             $error .= "{$val} =》删除失败！<br/>";
                     }
                     $this->error($error);
                 }
             }

             if($_GET['del']){
                 $tablePATH = $dataPATH."/".$_GET['del'];
                 
                 if(file_exists($tablePATH)){
                      $this->deleteDir($tablePATH);
                 }
                 if(!file_exists($tablePATH)){
                      $this ->success("表：{$_GET['del']} 备份删除成功！");
                 }else{
                      $this ->error("表：{$_GET['del']} 备份删除失败！"); 
                 }
             }
         }

         //删除目录
         private function deleteDir($dataPATH){
                import("@.ORG.Dir");
                $dirObj   = new Dir();
                $dirObj   ->delDir($dataPATH);
         }

         /*+---------------------------------+
           |     数据备份                    |
           +---------------------------------+*/
         public function backupDatabase(){
                //显示所有表信息
                $tab  = $this->allTable();
                $this ->assign("tableInfo",$this->ifBackUp($tab));
                $this ->display();
         }

         //执行备份
         public function executeBackUp(){

             import("@.ORG.BakDB"); 
	         $connectid = mysql_connect('localhost','root','xuwenqiang');
             $backupDir = $_SERVER['DOCUMENT_ROOT'].__ROOT__."/WebsiteDatabaseBackUp/";
             $DbBak     = new DbBak($connectid,$backupDir);

             if($_POST['allBackUp']){
                    
                    $DbBak     ->backupDb($_SESSION[C("DATA_KEY")]);
                    //判断是否已经全部备份
                    $info = $this ->fileExists();
                    if($info == null){
                           $this->success("数据库全部备份成功！");
                    }elseif($info == false){
                           $this->error("数据库全部备份失败！");
                    }elseif(count($info)>0){
                           $error = "表：<br/>";
                           foreach($info as $key => $val){
                                  $error .= $val."<br/>";
                           }
                           $error .= "未备份成功！";
                           $this->error($error);
                    }
                    
             }

             if($_POST['backup']){
                 $num       = count($_POST['tableName']);
                 if($num == 0){
                      $this->error("请勾选要备份的表！");
                 }elseif($num == 1){
                      $table  = $_POST['tableName'][0];
                 }elseif($num > 1){
                      $table  = $_POST['tableName'];
                 }
                 if($num != 0){
                        $DbBak     ->backupDb($_SESSION[C("DATA_KEY")],$table);
                        //获取表备份文件列表
                        $tabBakFile= $this->tableList();
                 }
                 if($num == 1){
                     if(in_array($table,$tabBakFile)){
                          $this ->success("成功了备份了表：{$table}!");
                     }else{
                          $this ->error("{$table} 表，备份失败！");
                     }
                 }
                 if($num > 1){
                        foreach($table as $key => $val){
                            if(!in_array($val,$tabBakFile)){
                                    $errorBakTab[] = $val;
                            }
                        }
                        if($errorBakTab == null){
                            foreach($table as $key => $val){
                                   $success.="{$val} 表 =》备份成功！<br/>";
                            }
                                   $this->success($success);
                        }else{
                            foreach($errorBakTab as $key => $val){
                                   $error.="{$val} 表 =》备份失败！<br/>";
                            } 
                            $this ->error($error);
                        }
                 }
             }

             if($_GET['tableName']){
                 $DbBak->backupDb($_SESSION[C("DATA_KEY")],$_GET['tableName']);
                 $tabBakFile= $this->tableList();
                 if(in_array($_GET['tableName'],$tabBakFile)){
                     $this ->success("成功的备份了表：{$_GET['tableName']}!");
                 }else{
                     $this ->error("{$_GET['tableName']} 表，备份失败！");
                 }
             }
         }

         //执行备份
         public function executeRecover(){

             import("@.ORG.BakDB"); 
	         $connectid = mysql_connect('localhost','root','xuwenqiang');
             $backupDir = $_SERVER['DOCUMENT_ROOT'].__ROOT__."/WebsiteDatabaseBackUp/";
             $DbBak     = new DbBak($connectid,$backupDir);

             if($_POST['allRecover']){
                    
                    
                 //判断是否已经全部备份
                 $info = $this ->fileExists();
                 $dataPATH = $backupDir.$_SESSION[C("DATA_KEY")];
                 if(file_exists($dataPATH)){
                    
                    if($info == null){
                           $DbBak ->restoreDb($_SESSION[C("DATA_KEY")]);
                           $this->success("数据库全部恢复成功！");
                    }elseif($info == "no"){
                           $this->error("数据库全部恢复失败！");
                    }elseif(count($info)>0){
                           $error = "表：<br/>\t\t";
                           foreach($info as $key => $val){
                                  $error .= $val."<br/>";
                           }
                           $error .= "未进行备份，不能全部表恢复！";
                           $this->error($error);
                    }
                 }else{
                      $this->error("数据库全部恢复失败！"); 
                 }
             }

             if($_POST['recover']){
                 //获取表备份文件列表
                 $tabBakFile= $this->tableList();
                 $num       = count($_POST['tableName']);
                 if($num == 0){
                      $this->error("请勾选要恢复的表！");
                 }elseif($num == 1){
                     $table  = $_POST['tableName'][0];
                     if(!in_array($table,$tabBakFile)){
                             $this ->error("{$table} 表未备份，恢复失败！");
                     }else{
                             $DbBak     ->restoreDb($_SESSION[C("DATA_KEY")],$table);
                             $success = "{$table} 表恢复成功！";
                             $this      ->success($success);
                     }
                 }elseif($num > 1){
                     $table  = $_POST['tableName'];
                     foreach($table as $key => $val){
                            if(!in_array($val,$tabBakFile)){
                                    $errorBakTab[] = $val;
                            }else{
                                    $success.="{$val} 表恢复成功！<br/>";
                            }
                     }
                     if($errorBakTab != null){
                            foreach($errorBakTab as $key => $val){
                                   $error.="{$val} 表未备份 =》恢复失败！<br/>";
                            } 
                            $this ->error($error);
                     }else{
                            $DbBak     ->restoreDb($_SESSION[C("DATA_KEY")],$table);
                            $this      ->success($success);
                            
                     }
                 }
             }

             if($_GET['tableName']){
                 $tablePATH = $backupDir."/".$_SESSION[C("DATA_KEY")]."/".$_GET['tableName']."/".$_GET['tableName'].".sql";
                 if(file_exists($tablePATH)){
                     $DbBak->restoreDb($_SESSION[C("DATA_KEY")],$_GET['tableName']);
                 }
                 $tabBakFile= $this->tableList();
                 if(in_array($_GET['tableName'],$tabBakFile)){
                     $this ->success("成功的恢复了表：{$_GET['tableName']}!");
                 }else{
                     $this ->error("{$_GET['tableName']} 表未备份，恢复失败！");
                 }
             }
         }

         /*+---------------------------------+
           |     数据恢复                    |
           +---------------------------------+*/
         public function recoverDatabase(){
                //显示所有表信息
                $tab  = $this->allTable();
                $this ->assign("tableInfo",$this->ifBackUp($tab));
                $this ->display();
         }

         public function ifBackUp($tableName){
                //1.获取数据库备份目录结构
                $dataArray = $this ->databaseList();
                //2.此站点数据库的目录是否存在，若不存在，所有表标记为为备份，若存在
                //获取此数据库目录下的目录数组，表目录存在则标记为已备份
                foreach($tableName as $key => $val){
                        $tableArray[] = $val["Tables_in_".$_SESSION[C('DATA_KEY')]];
                }
                if(in_array($_SESSION[C("DATA_KEY")],$dataArray)){
                        //获取表列表
                        $tabList  = $this->tableList();
                        foreach($tableArray as $key => $val){
                                $newtableArray[$key]['tableName'] = $val;
                                if(in_array($val,$tabList)){
                                        $newtableArray[$key]['status'] = "1";
                                }else{
                                        $newtableArray[$key]['status'] = "0";
                                }
                        }
                        //获取备份文件的创建、修改、访问时间，以及备份文件的大小
                        $tabInfo = $this ->tableListInfo($newtableArray);
                        $newtableArray = array();
                        $newtableArray = $tabInfo;
                        
                }else{
                        //所有表标记为未备份
                        foreach($tableArray as $key => $val){
                                $newtableArray[$key]['tableName'] = $val;
                                $newtableArray[$key]['status'] = "0";
                        }
                }

                return $newtableArray;

         }

         //获取数据库目录列表
         public function databaseList(){
                import("@.ORG.Dir");
                $dataPATH = $_SERVER['DOCUMENT_ROOT'].__ROOT__."/WebsiteDatabaseBackUp/";
                $dirObj   = new Dir();
                $dirArray = $dirObj->getList($dataPATH);
                return $dirArray;
         }

         //获取表目录列表
         public function tableList(){
                import("@.ORG.Dir");
                $dataPATH = $_SERVER['DOCUMENT_ROOT'].__ROOT__."/WebsiteDatabaseBackUp/".$_SESSION[C("DATA_KEY")];
                $dirObj   = new Dir();
                $dirArray = $dirObj->getList($dataPATH);
                return $dirArray;
         }

         //获取备份文件的详细信息
         public function tableListInfo($tabList){
             foreach($tabList as $key => $val){
                 if($val != "." && $val != ".."){
                     $dataPATH = $_SERVER['DOCUMENT_ROOT'].__ROOT__."/WebsiteDatabaseBackUp/".$_SESSION[C("DATA_KEY")]."/".$val["tableName"]."/".$val['tableName'].".sql";            
                     if(file_exists($dataPATH)){
                            $tabList[$key]['atime']    = date("Y-m-d",fileatime($dataPATH));   //上次访问时间   
                            $tabList[$key]['ctime']    = date("Y-m-d H:i:s",filectime($dataPATH));   //创建时间 
                            $tabList[$key]['mtime']    = date("Y-m-d H:i:s",filemtime($dataPATH));   //上次修改时间 
                            $tabList[$key]['filesize'] = $this ->getFileSize(filesize($dataPATH));   //文件大小 
                     }
                 }
             }
             return $tabList;
                
         }

         //获取站点数据库所有表名称
         public function allTable(){
                $this   ->changeDB();
                $tables = new Model();
                $tab    = $tables ->query("show tables");
                return $tab;
         }
         //判断文件是否存在
         public function fileExists(){
                //判断数据库目录是否存在
                $dataPATH = $_SERVER['DOCUMENT_ROOT'].__ROOT__."/WebsiteDatabaseBackUp/".$_SESSION[C("DATA_KEY")];
                if(file_exists($dataPATH)){
                      //获取数据库目录下的表目录
                      $tableList = $this->tableList();
                      $allTable  = $this->allTable();
                      foreach($allTable as $key => $val){
                              $tableArray[] = $val["Tables_in_".$_SESSION[C('DATA_KEY')]];
                      }
                      foreach($tableArray as $key => $val){
                          if(!in_array($val,$tableList)){
                                 if($val != "." && $val != ".." && $val != ".svn"){
                                     $errorTab[] = $val;
                                 }
                          }
                      }
                      return $errorTab;
                }else{
                      return "no"; 
                }
                
         }

         //获取文件大小
         public function getFileSize($bytes){
             if($bytes>=pow(2,40)){
                 $return = round($bytes/pow(1024,4),2);
                 $suffix = "TB";
             }else if($bytes>=pow(2,30)){
                 $return = round($bytes/pow(1024,3),2);
                 $suffix = "GB";
             }else if($bytes>=pow(2,20)){
                 $return = round($bytes/pow(1024,2),2);
                 $suffix = "MB";
             }else if($bytes>=pow(2,10)){
                 $return = round($bytes/pow(1024,1),2);
                 $suffix = "KB";
             }else{
                 $return = $bytes;
                 $suffix = "Byte";
             }

             return $return." ".$suffix;
         }
}
?>
